package com.ruoyi.system.api.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.JPushConfig;
import com.ruoyi.common.config.PushConfig;
import com.ruoyi.common.jpush.JPushClientUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.CcService;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.service.IPlanDetailsService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.util.ObjectUtils;

/**
 * 工程师FSE计划详情 工程师FSE计划详情Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-03
 */
@Service
public class PlanDetailsServiceImpl implements IPlanDetailsService {
    private static final Logger log = LoggerFactory.getLogger(PlanDetailsServiceImpl.class);

    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;

    @Autowired
    private ServiceNoticeMapper serviceNoticeMapper;

    @Autowired
    private StServiceReportMapper stServiceReportMapper;

    @Autowired
    private BatchLogMapper batchLogMapper;

    @Autowired
    private CcService ccService;

    @Autowired
    private JPushConfig jPushConfig;

    @Autowired
    private JpushLogMapper jpushLogMapper;

    @Autowired
    private UserMapper userMapper;


    /**
     * 配置文件
     */
    @Autowired
    private Global global;

    /**
     * 用户历史位置表
     */
    @Autowired
    private FseLocationLogMapper fseLocationLogMapper;

    @Autowired
    private InstrumentInfoMapper instrumentInfoMapper;

    @Autowired
    private ReportInfoMapper stReportInfoMapper;


    /**
     * 查询工程师FSE计划详情 工程师FSE计划详情
     *
     * @param id 工程师FSE计划详情 工程师FSE计划详情ID
     * @return 工程师FSE计划详情 工程师FSE计划详情
     */
    @Override
    public PlanDetails selectStPlanDetailsById(Long id) {

        PlanDetails planDetailsCurry = planDetailsMapper.selectStPlanDetailsById(id);
        if ("1".equals(planDetailsCurry.getState())) {
            PlanDetails searchPlanDetails = new PlanDetails();
            searchPlanDetails.setFillInLog("0");
            searchPlanDetails.setServiceNoticeId(planDetailsCurry.getServiceNoticeId());
            searchPlanDetails.setFseId(planDetailsCurry.getFseId());
            List<PlanDetails> planDetailsList = planDetailsMapper.selectStPlanDetailsList(searchPlanDetails);
            if (planDetailsList.size() > 0) {
                for (PlanDetails planDetails : planDetailsList) {
                    if (!"1".equals(planDetails.getState())) {
                        return planDetails;
                    }

                }
            }
        }
        return planDetailsCurry;
    }

    /**
     * 查询工程师FSE计划详情 工程师FSE计划详情列表
     *
     * @param stPlanDetails 工程师FSE计划详情 工程师FSE计划详情
     * @return 工程师FSE计划详情 工程师FSE计划详情
     */
    @Override
    public List<PlanDetails> selectStPlanDetailsList(PlanDetails stPlanDetails) {
        return planDetailsMapper.selectStPlanDetailsListByState(stPlanDetails);
    }

    /**
     * 新增工程师FSE计划详情 工程师FSE计划详情
     *
     * @param stPlanDetails 工程师FSE计划详情 工程师FSE计划详情
     * @return 结果
     */
    @Override
    public int insertStPlanDetails(PlanDetails stPlanDetails) {
        stPlanDetails.setCreateTime(DateUtils.getNowDate());
        return planDetailsMapper.insertStPlanDetails(stPlanDetails);
    }

    /**
     * 修改工程师FSE计划详情 工程师FSE计划详情
     *
     * @param stPlanDetails 工程师FSE计划详情 工程师FSE计划详情
     * @return 结果
     */
    @Override
    public int updateStPlanDetails(PlanDetails stPlanDetails) {
        stPlanDetails.setUpdateTime(DateUtils.getNowDate());
        return planDetailsMapper.updateStPlanDetails(stPlanDetails);
    }

    /**
     * 删除工程师FSE计划详情 工程师FSE计划详情对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStPlanDetailsByIds(String ids) {
        return planDetailsMapper.deleteStPlanDetailsByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除工程师FSE计划详情 工程师FSE计划详情信息
     *
     * @param id 工程师FSE计划详情 工程师FSE计划详情ID
     * @return 结果
     */
    @Override
    public int deleteStPlanDetailsById(Long id) {
        return planDetailsMapper.deleteStPlanDetailsById(id);
    }

    @Override
    public ResponseWithData<?> getFseStateCounts(String EnginnerId) {
        List<ServiceDetails> list = planDetailsMapper.getFseStateCounts(EnginnerId);
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getFsePlan(String EnginnerId, String StartTime, String EndTime) {
        List<PlanDetails> list = planDetailsMapper.getFsePlan(EnginnerId, StartTime, EndTime, null);
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> fseAccept(String ServiceNoticeIds, String serviceNos, String planIds, String EnginnerId, String serviceRole, String StartTime, String workingHours, String EndTime,Double signOffAutoHour) throws Exception {
        String[] sns = ServiceNoticeIds.split(",");
        String[] ps = planIds.split(",");
        String[] snos = serviceNos.split(",");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date acceptTime = new Date();
        List<Map<String, String>> offLineDatas = new ArrayList<>();

//        PlanDetails planDetails2 = new PlanDetails();
//        planDetails2.setFseId(EnginnerId);
//        planDetails2.setState("'1','2','3'");
//        planDetails2.setEstimatedVisitingTime(sdf.parse(StartTime));
//        planDetails2.setEstimatedDepartureTime(sdf.parse(EndTime));
//        planDetails2.setPlanIds(planIds);
//        List<PlanDetails> planDetailsL = planDetailsMapper.checkPlanDetailsList(planDetails2);
//        if(planDetailsL!=null && planDetailsL.size()>0){
//            return new ResponseWithData<>().error().msg("预计上门时间冲突").code(201);
//        }

        for (int i = 0; i < sns.length; i++) {
            Map<String, String> offLineData = new HashMap<>();

            ServiceDetails serviceDetailsSeachTL = new ServiceDetails();
            serviceDetailsSeachTL.setServiceNoticeId(new Long(sns[i].toString()));
            serviceDetailsSeachTL.setFseId(EnginnerId);
            serviceDetailsSeachTL.setDelFlag("0");
            List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(serviceDetailsSeachTL);
            ServiceDetails detailsObj = serviceDetailsList.get(0);
            /** 调用CC端接口2.14接受服务 */
            JSONObject jsonObject = ccService.acceptService(EnginnerId, snos[i], sdf2.format(acceptTime), StartTime + ":00", detailsObj.getTeamleaderId(), detailsObj.getSendTime());
            if ("200".equals(jsonObject.getString("code"))) {
                String ServiceNoticeId = sns[i];
                /** 更新st_service_notice表 */
                ServiceNotice serviceNotice = new ServiceNotice();
                serviceNotice.setAppState(2L);//【2服务中】
                serviceNotice.setId(Long.parseLong(ServiceNoticeId));
                serviceNoticeMapper.updateServiceNotice(serviceNotice);
                /** 更新st_service_details表 */
                ServiceDetails serviceDetails = new ServiceDetails();
                serviceDetails.setFseId(EnginnerId);
                // serviceDetails.setServiceNo(serviceNo);
                serviceDetails.setState(1L); //【1已接受】
                serviceDetails.setServiceRole(serviceRole);
                serviceDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
                serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                /** 更新st_plan_details表 */
                PlanDetails planDetails = new PlanDetails();
                planDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
                // planDetails.setServiceNo(serviceNo);
                planDetails.setId(Long.parseLong(ps[i]));
                planDetails.setFseId(EnginnerId);
                planDetails.setEstimatedVisitingTime(sdf.parse(StartTime));
                planDetails.setEstimatedWorkingHours(workingHours);
                planDetails.setEstimatedDepartureTime(sdf.parse(EndTime));
                planDetails.setIsAccept("1");//【1接受】
                planDetails.setState("1");//【1已接受】
                PlanDetails planDetailsSearch = new PlanDetails();
                planDetailsSearch.setServiceNo(snos[i]);
                planDetailsSearch.setFseId(EnginnerId);
                planDetailsSearch.setIsAccept("1");
                List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);
                planDetails.setAcceptTime(acceptTime);
                planDetails.setSignOffAutoHour(signOffAutoHour);
                if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList)) {
                    if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList.get(0).getAcceptTime())) {
                        planDetails.setAcceptTime(planDetailsListlanDetailsList.get(0).getAcceptTime());
                    }
                }


                // planDetails.setServiceRole(serviceRole);
                planDetailsMapper.updateStPlanDetails(planDetails);

                ServiceNotice serviceNotice1 = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
                InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(snos[i]);
                if (instrumentInfo != null && instrumentInfo.getId() != null) {
                    offLineData.put("serviceNo", snos[i]);
                    offLineData.put("serviceNoticeId", sns[i]);
                    offLineData.put("planId", planDetails.getId() + "");
                    offLineData.put("customerName", serviceNotice1.getCustomerName());
                    offLineData.put("instrumentId", instrumentInfo.getId() + "");
                    offLineData.put("instSn", instrumentInfo.getInstSn());
                    offLineData.put("acceptTime", sdf.format(acceptTime));
                    offLineData.put("serviceType", serviceNotice1.getServiceType());
                    offLineData.put("subServiceType", serviceNotice1.getSubServiceType());
                }

                offLineDatas.add(offLineData);
            } else {
                System.out.println("接受失败");
            }
            /** 更新操作日志表 */
            BatchLog batchLog = new BatchLog();
            batchLog.setEnginnerId(Long.parseLong(EnginnerId));
            batchLog.setPlanId(Long.parseLong(ps[i]));
            batchLog.setServiceNo(snos[i]);
            batchLog.setCreateTime(new Date());
            batchLog.setBatchType(4L);
            batchLogMapper.insertBatchLog(batchLog);

            /** ========================= 未完待续 ======================================================= */

        }

        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);
    }


    @Override
    public ResponseWithData<?> updatefseAccept(String ServiceNoticeIds, String serviceNos, String planIds, String EnginnerId, String serviceRole, String StartTime, String workingHours, String EndTime, String enginnerName, Double signOffAutoHour) throws Exception {
        // 离线数据处理
        List<Map<String, String>> offLineDatas = new ArrayList<>();
        String[] sns = ServiceNoticeIds.split(",");
        String[] ps = planIds.split(",");
        String[] snos = serviceNos.split(",");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date acceptTime = new Date();

        for (int i = 0; i < sns.length; i++) {
            // 查看该服务是否有未提交的报告。
            ReportInfo reportInfo = new ReportInfo();
            reportInfo.setServiceNo(snos[i]);
            reportInfo.setEnginnerId(new Long(EnginnerId));
            reportInfo.setDelFlag("0");
            List<ReportInfo> reportInfoList = stReportInfoMapper.selectStReportInfoList(reportInfo);
            // 未提交報告
            String isSubmmitReport = "0";
            if (reportInfoList.size() > 0) {
                // 未提交報告
                for (ReportInfo reportInfoobj : reportInfoList) {
                    if ("1".equals(reportInfoobj.getSyncFlag()) && "1".equals(reportInfoobj.getServiceResult())) {
                        isSubmmitReport = "1";
                        break;
                    }
                }
            }

            if ("0".equals(isSubmmitReport)) {

                ServiceDetails newServiceDetails = new ServiceDetails();
                newServiceDetails.setFseId(EnginnerId);
                newServiceDetails.setServiceNoticeId(new Long(sns[i]));
                List<ServiceDetails> serviceDetailsListSearch = serviceDetailsMapper.selectServiceDetailsList(newServiceDetails);

                if (serviceDetailsListSearch.size() > 0) {
                    ServiceDetails searchServiceDetails = serviceDetailsListSearch.get(0);
                    if ("4".equals(searchServiceDetails.getState().toString())) {
                        PlanDetails newPlan = new PlanDetails();
                        newPlan.setServiceNoticeId(Long.parseLong(sns[i]));
                        newPlan.setServiceNo(snos[i]);
                        newPlan.setFseId(EnginnerId);
                        newPlan.setFseName(enginnerName);
                        newPlan.setIsAccept("1");
                        newPlan.setEstimatedDepartureTime(sdf.parse(EndTime));
                        newPlan.setEstimatedVisitingTime(sdf.parse(StartTime));
                        newPlan.setEstimatedWorkingHours(workingHours);
                        newPlan.setState("1");
                        newPlan.setCreateTime(acceptTime);
                        newPlan.setSignOffAutoHour(signOffAutoHour);
                        newPlan.setAcceptTime(acceptTime);

                        PlanDetails planDetailsSearch = new PlanDetails();
                        planDetailsSearch.setServiceNo(snos[i]);
                        planDetailsSearch.setFseId(EnginnerId);
                        planDetailsSearch.setIsAccept("1");
                        List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);

                        if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList)) {
                            if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList.get(0).getAcceptTime())) {
                                newPlan.setAcceptTime(planDetailsListlanDetailsList.get(0).getAcceptTime());
                            }
                        }

                        planDetailsMapper.insertStPlanDetails(newPlan);

                        ServiceDetails serviceDetails = new ServiceDetails();
                        serviceDetails.setFseId(EnginnerId);
                        serviceDetails.setState(3L);
                        serviceDetails.setServiceNoticeId(Long.parseLong(sns[i]));
                        serviceDetails.setUpdateBy(newPlan.getId() + "");
                        serviceDetailsMapper.updateMyServiceDetails(serviceDetails);

                    } else {


                        PlanDetails planDetailsSearch = new PlanDetails();
                        planDetailsSearch.setServiceNoticeId(new Long(sns[i]));
                        planDetailsSearch.setFseId(EnginnerId);
                        planDetailsSearch.setState("1");
                        List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);
                        if (planDetailsListlanDetailsList.size() > 0) {
                            PlanDetails curryPlanDetails = planDetailsListlanDetailsList.get(0);
                            curryPlanDetails.setServiceNoticeId(Long.parseLong(sns[i]));
                            curryPlanDetails.setServiceNo(snos[i]);
                            curryPlanDetails.setFseId(EnginnerId);
                            curryPlanDetails.setFseName(enginnerName);
                            curryPlanDetails.setIsAccept("1");
                            curryPlanDetails.setEstimatedDepartureTime(sdf.parse(EndTime));
                            curryPlanDetails.setEstimatedVisitingTime(sdf.parse(StartTime));
                            curryPlanDetails.setEstimatedWorkingHours(workingHours);
                            curryPlanDetails.setSignIn("0");
                            curryPlanDetails.setState("1");
                            curryPlanDetails.setSignOff("0");
                            curryPlanDetails.setCreateTime(new Date());
                            curryPlanDetails.setAcceptTime(acceptTime);
                            curryPlanDetails.setSignOffAutoHour(signOffAutoHour);
                            PlanDetails planDetailsSearch2 = new PlanDetails();
                            planDetailsSearch2.setServiceNo(snos[i]);
                            planDetailsSearch2.setFseId(EnginnerId);
                            planDetailsSearch2.setIsAccept("1");
                            List<PlanDetails> planDetailsListlanDetailsList2 = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);

                            if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList2)) {
                                if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList2.get(0).getAcceptTime())) {
                                    curryPlanDetails.setAcceptTime(planDetailsListlanDetailsList2.get(0).getAcceptTime());
                                }
                            }

                            planDetailsMapper.updateStPlanDetails(curryPlanDetails);


                            ServiceDetails serviceDetails = new ServiceDetails();
                            serviceDetails.setFseId(EnginnerId);
                            serviceDetails.setState(3L);
                            serviceDetails.setServiceNoticeId(Long.parseLong(sns[i]));
                            //serviceDetails.setUpdateBy(newPlan.getId()+"");
                            serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                        } else {
                            PlanDetails newPlan = new PlanDetails();
                            newPlan.setServiceNoticeId(Long.parseLong(sns[i]));
                            newPlan.setServiceNo(snos[i]);
                            newPlan.setFseId(EnginnerId);
                            newPlan.setFseName(enginnerName);
                            newPlan.setIsAccept("1");
                            newPlan.setEstimatedDepartureTime(sdf.parse(EndTime));
                            newPlan.setEstimatedVisitingTime(sdf.parse(StartTime));
                            newPlan.setEstimatedWorkingHours(workingHours);
                            newPlan.setState("1");
                            newPlan.setCreateTime(acceptTime);
                            newPlan.setAcceptTime(acceptTime);
                            newPlan.setSignOffAutoHour(signOffAutoHour);
                            PlanDetails planDetailsSearch2 = new PlanDetails();
                            planDetailsSearch2.setServiceNo(snos[i]);
                            planDetailsSearch2.setFseId(EnginnerId);
                            planDetailsSearch2.setIsAccept("1");
                            List<PlanDetails> planDetailsListlanDetailsList2 = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch2);

                            if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList2)) {
                                if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList2.get(0).getAcceptTime())) {
                                    newPlan.setAcceptTime(planDetailsListlanDetailsList2.get(0).getAcceptTime());
                                }
                            }
                            planDetailsMapper.insertStPlanDetails(newPlan);

                            ServiceDetails serviceDetails = new ServiceDetails();
                            serviceDetails.setFseId(EnginnerId);
                            serviceDetails.setState(3L);
                            serviceDetails.setServiceNoticeId(Long.parseLong(sns[i]));
                            serviceDetails.setUpdateBy(newPlan.getId() + "");
                            serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                        }


                    }
                }


                /** 更新操作日志表 */
                BatchLog batchLog = new BatchLog();
                batchLog.setEnginnerId(Long.parseLong(EnginnerId));
                batchLog.setPlanId(Long.parseLong(ps[i]));
                batchLog.setServiceNo(snos[i]);
                batchLog.setCreateTime(acceptTime);
                batchLog.setBatchType(2L);
                batchLogMapper.insertBatchLog(batchLog);


                // 离线数据处理
                Map<String, String> offLineData = new HashMap<>();

                ServiceDetails detailTemp = new ServiceDetails();
                detailTemp.setFseId(EnginnerId);
                detailTemp.setServiceNoticeId(new Long(sns[i]));
                detailTemp.setServiceNo(snos[i]);
                List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(detailTemp);
                ServiceDetails details = serviceDetailsList.get(0);
                offLineData.put("serviceNo", details.getServiceNo());
                offLineData.put("serviceNoticeId", details.getServiceNoticeId() + "");
                offLineData.put("planId", details.getUpdateBy());
                ServiceNotice serviceNotice1 = serviceNoticeMapper.selectServiceNoticeById(new Long(sns[i]));
                offLineData.put("serviceType", serviceNotice1.getServiceType());
                offLineData.put("subServiceType", serviceNotice1.getSubServiceType());

                InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(details.getServiceNo());
                offLineData.put("instrumentId", instrumentInfo.getId() + "");
                offLineData.put("instSn", instrumentInfo.getInstSn());

                // 查询最新的计划
                PlanDetails planDetailTemp = new PlanDetails();
                planDetailTemp.setServiceNoticeId(new Long(sns[i]));
                planDetailTemp.setFseId(EnginnerId);
                planDetailTemp.setIsAccept("1");
                planDetailTemp.setSignIn("0");
                PlanDetails planDetailsSignIn = planDetailsMapper.getPlanDetailsBySignInByNoticeId(planDetailTemp);
                offLineData.put("acceptTime", sdf.format(planDetailsSignIn.getAcceptTime()));
                offLineDatas.add(offLineData);

            }




            //   else {
            //以前的操作
//             PlanDetails newPlan = new PlanDetails();
//             newPlan.setServiceNoticeId(Long.parseLong(sns[i]));
//             newPlan.setServiceNo(snos[i]);
//             newPlan.setFseId(EnginnerId);
//             newPlan.setFseName(enginnerName);
//             newPlan.setIsAccept("1");
//             newPlan.setEstimatedDepartureTime(sdf.parse(EndTime));
//             newPlan.setEstimatedVisitingTime(sdf.parse(StartTime));
//             newPlan.setEstimatedWorkingHours(workingHours);
//             newPlan.setState("1");
//             newPlan.setCreateTime(acceptTime);
//             newPlan.setAcceptTime(acceptTime);
//             planDetailsMapper.insertStPlanDetails(newPlan);
//
//             ServiceDetails serviceDetails = new ServiceDetails();
//             serviceDetails.setFseId(EnginnerId);
//             serviceDetails.setState(3L);
//             serviceDetails.setServiceNoticeId(Long.parseLong(sns[i]));
//             serviceDetails.setUpdateBy(newPlan.getId()+"");
//             serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
//
//
//             PlanDetails planDetails = new PlanDetails();
//             planDetails.setId(Long.parseLong(ps[i]));
////            planDetails.setSignOff("1");
////            planDetails.setSignOffLon(Double.parseDouble(longitude));
////            planDetails.setSignOffLat(Double.parseDouble(latitude));
//             planDetails.setState("3");
////            planDetails.setSignOffTime(date);
//             planDetailsMapper.updateStPlanDetails(planDetails);
//
//
//
//             /** 更新操作日志表 */
//             BatchLog batchLog = new BatchLog();
//             batchLog.setEnginnerId(Long.parseLong(EnginnerId));
//             batchLog.setPlanId(Long.parseLong(ps[i]));
//             batchLog.setServiceNo(snos[i]);
//             batchLog.setCreateTime(acceptTime);
//             batchLog.setBatchType(2L);
//             batchLogMapper.insertBatchLog(batchLog);


            //       }


        }

        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);
    }


    @Override
    public ResponseWithData<?> fseRefuse(String ServiceNoticeId, String serviceNo, String EnginnerId, String refusalReasons, String planId, String enginnerName) throws Exception {
        ServiceDetails serviceDetails = new ServiceDetails();
        serviceDetails.setState(6L);
        serviceDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
        serviceDetails.setRefusalReasons(refusalReasons);
        serviceDetails.setFseId(EnginnerId);
        serviceDetailsMapper.updateMyServiceDetails(serviceDetails);

        PlanDetails planDetails = new PlanDetails();
        planDetails.setIsAccept("0");
        planDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
        planDetails.setServiceNo(serviceNo);
        planDetails.setFseId(EnginnerId);
        planDetails.setRefusalReasons(refusalReasons);
        planDetails.setState("6");
        planDetails.setId(Long.parseLong(planId));
        planDetailsMapper.updateStPlanDetails(planDetails);

        /** FSE拒绝后消息推送给TL */


        List<User> users1 = userMapper.getUserByServiceNoticeId(ServiceNoticeId);

        if (users1 != null && users1.size() > 0 && StringUtils.isNotEmpty(users1.get(0).getRegistrationId())) {
            // 推送额外参数
            JsonObject extra = new JsonObject();
            extra.addProperty("type", PushConfig.REFUSE_STATE);
            extra.addProperty("serviceNoticeId", ServiceNoticeId);
            extra.addProperty("serviceNo", serviceNo);

            ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(new Long(ServiceNoticeId));
            String teamleaderIdtemp = "";
            if (serviceNotice != null) {
                if (serviceNotice.getTeamleaderId() != null) {
                    teamleaderIdtemp = serviceNotice.getTeamleaderId();
                }
            }
            if (!"".equals(teamleaderIdtemp)) {
                extra.addProperty("teamleaderId", teamleaderIdtemp);
            } else {
                teamleaderIdtemp = users1.get(0).getEnginnerId() + "";
                extra.addProperty("teamleaderId", teamleaderIdtemp);
            }

            extra.addProperty("EnginnerId", EnginnerId);
            String content = PushConfig.REFUSE_CONTENT.replaceAll("NAME", enginnerName).replaceAll("NO", serviceNo);

            JpushLog jpushLog = new JpushLog();
            PushResult pushResult = null;
            try {
                JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                User user = new User();
                user.setEnginnerId(new Long(teamleaderIdtemp));
                List<User> userList = userMapper.selectUserList(user);
                if (userList.size() > 0) {
                    pushResult = JPushClientUtil.getInstance().sendPush(userList.get(0).getRegistrationId(), PushConfig.REFUSE_TITLE, content, extra);

                    jpushLog.setStatuscode(pushResult.statusCode + "");
                    jpushLog.setMsgId(pushResult.msg_id + "");
                    jpushLog.setSendno(pushResult.sendno + "");
                }

            } catch (APIConnectionException e) {
                // Connection error, should retry later
                log.error("Connection error, should retry later", e);
            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                log.error("Should review the error, and fix the request", e);
                log.info("HTTP Status: " + e.getStatus());
                log.info("Error Code: " + e.getErrorCode());
                log.info("Error Message: " + e.getErrorMessage());
                jpushLog.setStatuscode(e.getErrorCode() + "");
                jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
            }
            // 保存推送日志
            jpushLog.setEnginnerId(users1.get(0).getEnginnerId() + "");
            jpushLog.setType(PushConfig.ONE_PUSH);
            jpushLog.setRegistrationId(users1.get(0).getRegistrationId());
            jpushLog.setState(PushConfig.REFUSE_STATE);
            jpushLog.setNoticeId(Long.parseLong(ServiceNoticeId));
            jpushLog.setServiceNo(serviceNo);
            jpushLog.setTitle(PushConfig.REFUSE_TITLE);
            jpushLog.setContent(content);
            jpushLog.setExtra(extra.toString());
            jpushLog.setPushTime(new Date());
            jpushLog.setCreateTime(new Date());
            jpushLogMapper.insertJpushLog(jpushLog);
        }


        return new ResponseWithData<>().success().msg("操作成功").code(200);
    }

    @Override
    public ResponseWithData<?> fseSign(String ServiceNoticeIds, String serviceNos, String planIds, String EnginnerId, String longitude, String latitude, String relServiceNo) throws Exception {
        // System.out.println(" ---------qiandao-------star-------" + ServiceNoticeIds + "=================" + serviceNos + "----planIds========" + planIds);
        String[] sns = ServiceNoticeIds.split(",");
        String[] ps = planIds.split(",");
        String[] snos = serviceNos.split(",");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 离线数据
        List<Map<String, String>> offLineDatas = new ArrayList<>();
        // 关联的签到用一个时间方便后续查询
        Date date = new Date();
        for (int i = 0; i < sns.length; i++) {
            String ServiceNoticeId = sns[i];
            PlanDetails planDetailTemp = new PlanDetails();
            planDetailTemp.setServiceNoticeId(new Long(ServiceNoticeId));
            planDetailTemp.setFseId(EnginnerId);
            planDetailTemp.setIsAccept("1");
            planDetailTemp.setSignIn("0");
            PlanDetails planDetailsSignIn = planDetailsMapper.getPlanDetailsBySignInByNoticeId(planDetailTemp);
            if (planDetailsSignIn != null) {
                /** 更新st_service_details表 */
                ServiceDetails serviceDetails = new ServiceDetails();
                serviceDetails.setFseId(EnginnerId);
                serviceDetails.setState(2L);
                serviceDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
                serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                /** 更新st_plan_details表 */
                PlanDetails planDetailsSignInNew = new PlanDetails();
                //planDetailsSignInNew.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
                planDetailsSignInNew.setId(planDetailsSignIn.getId());
                //  planDetailsSignInNew.setFseId(EnginnerId);
                planDetailsSignInNew.setState("2");
                planDetailsSignInNew.setIsDoor("1");
                planDetailsSignInNew.setSignIn("1");
                planDetailsSignInNew.setSignInLon(Double.parseDouble(longitude));
                planDetailsSignInNew.setSignInLat(Double.parseDouble(latitude));
                planDetailsSignInNew.setSignInTime(date);
                planDetailsMapper.updateStPlanDetails(planDetailsSignInNew);


                /** 查询服务通知 是否前期有批量操作*/

//                BatchLog log=new BatchLog();
//                log.setPlanId(new Long(ps[i]));
//                log.setEnginnerId(new Long(EnginnerId));
//                log.setServiceNo(snos[i]);
//                log.setBatchType(new Long("1"));
//                List<BatchLog> batchLogList=  batchLogMapper.selectBatchLogList(log);
//                if(batchLogList.size()>0){
//                    BatchLog current =batchLogList.get(0);
//                    if(current.getRelServiceNo()!=null){
//                        current.setRelServiceNo(Null);
//                        batchLogMapper.updateBatchLog(current);
//                    }
//                }
                //   batchLog.setRelServiceNo(relServiceNo);

                /** 更新操作日志表 */
                BatchLog batchLog = new BatchLog();
                batchLog.setEnginnerId(Long.parseLong(EnginnerId));
                batchLog.setPlanId(Long.parseLong(ps[i]));
                batchLog.setServiceNo(snos[i]);
                batchLog.setCreateTime(date);
                batchLog.setBatchType(1L);
                if (sns.length > 1) {
                    batchLog.setRelServiceNo(relServiceNo);

                    ServiceDetails serviceDetailsSearch = new ServiceDetails();
                    serviceDetailsSearch.setServiceNo(relServiceNo);
                    serviceDetailsSearch.setFseId(EnginnerId);
                    List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(serviceDetailsSearch);
                    if (serviceDetailsList.size() > 0) {
                        batchLog.setRelPlanId(new Long(serviceDetailsList.get(0).getUpdateBy()));
                    }

                }

                batchLogMapper.insertBatchLog(batchLog);

            } else {

                return new ResponseWithData<>().success().msg("签到异常没有 " + ServiceNoticeId).code(200);
            }

            InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(snos[i]);
            Map<String, String> offLineData = new HashMap<>();
            ServiceNotice serviceNotice1 = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
            if (instrumentInfo != null && instrumentInfo.getId() != null) {
                offLineData.put("serviceNo", snos[i]);
                offLineData.put("serviceNoticeId", sns[i]);
                offLineData.put("planId", planDetailsSignIn.getId() + "");
                offLineData.put("instrumentId", instrumentInfo.getId() + "");
                offLineData.put("instSn", instrumentInfo.getInstSn());
                offLineData.put("acceptTime", sdf.format(planDetailsSignIn.getAcceptTime()));
                offLineData.put("signInTime", sdf2.format(date));
                offLineData.put("serviceType", serviceNotice1.getServiceType());
                offLineData.put("subServiceType", serviceNotice1.getSubServiceType());
            }
            offLineDatas.add(offLineData);
        }
        System.out.println("----qiandao--------end-------------" + ServiceNoticeIds + "=================" + serviceNos + "-----planIds========" + planIds);
        /** 调用高德api 根据经纬线逆解析用户所在地址 */
        String address = "";
        String url = global.getGaodeApi().replaceAll("KEY", global.getGaodeKey())
                .replaceAll("LOCATION", longitude + "," + latitude);
        Response res = OkHttpUtils.getInstance().getRequest(url.toString(), null);
        if (res.code() == 200) {
            String reponseBody = res.body().string();
            log.info("高德地址逆解析返回结果：" + reponseBody);
            JSONObject obj = JSON.parseObject(reponseBody);
            if ("1".equals(obj.getString("status"))) {
                address = obj.getJSONObject("regeocode").getString("formatted_address");
                log.info("高德逆解析地址：" + address);
            }
        }
        /** 签到位置信息存入log表中，用于轨迹查询 */
        List<User> userList = userMapper.getFseInformation(EnginnerId);
        FseLocationLog fseLocationLog = new FseLocationLog();
        fseLocationLog.setAddress(address);
        fseLocationLog.setFseId(EnginnerId);
        fseLocationLog.setFseName(userList.get(0).getName());
        fseLocationLog.setNetworkState("WWAN");
        fseLocationLog.setState("1");
        fseLocationLog.setPostx(Double.parseDouble(longitude));
        fseLocationLog.setPosty(Double.parseDouble(latitude));
        fseLocationLog.setCreateTime(date);
        fseLocationLog.setReceiveDate(date);
        fseLocationLog.setType("2");
        fseLocationLogMapper.insertFseLocationLog(fseLocationLog);


        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);
    }

    @Override
    public ResponseWithData<?> fseSignOff(String ServiceNoticeId, String serviceNo, String EnginnerId, String customerName, String signInTime, String longitude, String latitude, String state) throws Exception {

        //List<PlanDetails> pdList = planDetailsMapper.AssociatedCustomersByBatch(EnginnerId,serviceNo, customerName, signInTime,null,null ,"2",null);
        //批量订单
        //  List<PlanDetails> pdList = this.fseSignOffBatchPlain(ServiceNoticeId,EnginnerId,signInTime,null,null, state, planId);
//       if(pdList.size()==0){
//            pdList = planDetailsMapper.AssociatedCustomers(EnginnerId, customerName, signInTime,null,null ,"2",null);
//       }
        List<PlanDetails> pdList = planDetailsMapper.AssociatedCustomers(EnginnerId, customerName, signInTime, null, null, "2", null);
        // 关联的签离用一个时间方便后续查询
        // 离线数据
        List<Map<String, String>> offLineDatas = new ArrayList<>();

        Date date = new Date();
        if (pdList != null && pdList.size() > 0) {
            for (int i = 0; i < pdList.size(); i++) {
                ServiceDetails serviceDetails = new ServiceDetails();
                serviceDetails.setFseId(EnginnerId);
                serviceDetails.setState(Long.parseLong(state));
                serviceDetails.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                serviceDetailsMapper.updateMyServiceDetails(serviceDetails);

                PlanDetails planDetails = new PlanDetails();
                planDetails.setId(pdList.get(i).getId());
                planDetails.setSignOff("1");
                planDetails.setSignOffLon(Double.parseDouble(longitude));
                planDetails.setSignOffLat(Double.parseDouble(latitude));
                planDetails.setState(state);
                planDetails.setSignOffTime(date);
                planDetailsMapper.updateStPlanDetails(planDetails);

                /** 更新操作日志表 */
                BatchLog batchLog = new BatchLog();
                batchLog.setEnginnerId(Long.parseLong(EnginnerId));
                batchLog.setPlanId(pdList.get(i).getId());
                batchLog.setServiceNo(pdList.get(i).getServiceNo());
                batchLog.setCreateTime(new Date());
                batchLog.setBatchType(2L);
                batchLogMapper.insertBatchLog(batchLog);

                /****离线数据处理***/

                // 离线返回处理
                Map<String, String> offLineData = new HashMap<>();

                ServiceDetails detailTemp = new ServiceDetails();
                detailTemp.setFseId(EnginnerId);
                detailTemp.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                detailTemp.setServiceNo(pdList.get(i).getServiceNo());
                List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(detailTemp);
                ServiceDetails details = serviceDetailsList.get(0);
                offLineData.put("serviceNo", detailTemp.getServiceNo());
                offLineData.put("serviceNoticeId", detailTemp.getServiceNoticeId() + "");
                offLineData.put("planId", details.getUpdateBy());
                offLineDatas.add(offLineData);

            }

            /** 调用高德api 根据经纬线逆解析用户所在地址 */
            String address = "";
            String url = global.getGaodeApi().replaceAll("KEY", global.getGaodeKey())
                    .replaceAll("LOCATION", longitude + "," + latitude);
            Response res = OkHttpUtils.getInstance().getRequest(url.toString(), null);
            if (res.code() == 200) {
                String reponseBody = res.body().string();
                log.info("高德地址逆解析返回结果：" + reponseBody);
                JSONObject obj = JSON.parseObject(reponseBody);
                if ("1".equals(obj.getString("status"))) {
                    address = obj.getJSONObject("regeocode").getString("formatted_address");
                    log.info("高德逆解析地址：" + address);
                }
            }
            /** 签离位置信息存入log表中，用于轨迹查询 */
            FseLocationLog fseLocationLog = new FseLocationLog();
            fseLocationLog.setAddress(address);
            fseLocationLog.setFseId(EnginnerId);
            List<User> userList = userMapper.getFseInformation(EnginnerId);
            fseLocationLog.setFseName(userList.get(0).getName());
            fseLocationLog.setNetworkState("WWAN");
            fseLocationLog.setState("1");
            fseLocationLog.setPostx(Double.parseDouble(longitude));
            fseLocationLog.setPosty(Double.parseDouble(latitude));
            fseLocationLog.setCreateTime(date);
            fseLocationLog.setReceiveDate(date);
            fseLocationLog.setType("3");
            fseLocationLogMapper.insertFseLocationLog(fseLocationLog);

        }
        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);
    }


    public List<PlanDetails> fseSignOffBatchPlain(String ServiceNoticeId, String EnginnerId, String signInTime, String signIn, String fillInLog, String state, String planId) {

        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
        BatchLog batchlog = new BatchLog();
        batchlog.setServiceNo(serviceNotice.getServiceNo());
        batchlog.setEnginnerId(new Long(EnginnerId));
        batchlog.setPlanId(new Long(planId));
        List<BatchLog> batchLogList = batchLogMapper.selectBatchLogList(batchlog);
        String rel_service_no = "";
        for (BatchLog batchLog : batchLogList) {
            if (batchLog.getRelServiceNo() != null) {
                rel_service_no = batchLog.getRelServiceNo();
                break;
            }

        }
        List<PlanDetails> listBathPlanDetails = new ArrayList<>();
        if (!"".equals(rel_service_no)) {
            listBathPlanDetails = planDetailsMapper.AssociatedCustomersByBatch(EnginnerId, rel_service_no, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, "");

        }
        return listBathPlanDetails;
    }

    @Override
    public ResponseWithData<?> fseSignOffAgain(String ServiceNoticeId, String EnginnerId, String customerName, String signInTime, String longitude, String latitude, String state, String estimatedVisitingTime, String estimatedWorkingHours, String estimatedDepartureTime, Double signOffAutoHour) throws Exception {


        List<PlanDetails> pdList = planDetailsMapper.AssociatedCustomers(EnginnerId, customerName, signInTime, null, null, "2", null);
        // pdList = planDetailsMapper.AssociatedCustomers(EnginnerId, customerName, signInTime,null,null ,"2",null);
        // 关联的签离用一个时间方便后续查询
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 离线数据
        List<Map<String, String>> offLineDatas = new ArrayList<>();
        if (pdList != null && pdList.size() > 0) {
//            StringBuffer planIds = new StringBuffer();
//            for(int j=0;j<pdList.size();j++){
//                planIds.append(pdList.get(j).getId());
//                planIds.append(",");
//            }
//            String planIdss = planIds.toString().substring(0, planIds.toString().length()-1);
//            PlanDetails planDetails2 = new PlanDetails();
//            planDetails2.setFseId(EnginnerId);
//            planDetails2.setState("'1','2','3'");
//            planDetails2.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
//            planDetails2.setPlanIds(planIdss);
//            List<PlanDetails> planDetailsL = planDetailsMapper.checkPlanDetailsList(planDetails2);
//            if(planDetailsL!=null && planDetailsL.size()>0){
//                return new ResponseWithData<>().error().msg("预计上门时间冲突").code(201);
//            }

            for (int i = 0; i < pdList.size(); i++) {

                // 查看 对应的服务报告是否已经同步
                ReportInfo reportInfo = new ReportInfo();
                reportInfo.setServiceNo(pdList.get(i).getServiceNo());
                reportInfo.setEnginnerId(new Long(EnginnerId));
                reportInfo.setDelFlag("0");
                reportInfo.setPlanId(pdList.get(i).getId());
                reportInfo.setSyncFlag("1");
                reportInfo.setServiceResult("1");
                reportInfo.setRelServiceNo(new Long("1"));
                List<ReportInfo> reportInfoList = stReportInfoMapper.selectStReportInfoList(reportInfo);
                ServiceNotice serviceNotice1 = serviceNoticeMapper.selectServiceNoticeById(pdList.get(i).getServiceNoticeId());
                //  没有服务报告情况
                if (reportInfoList.size() == 0) {
                    PlanDetails newPlan = new PlanDetails();
                    newPlan.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                    newPlan.setServiceNo(pdList.get(i).getServiceNo());
                    newPlan.setFseId(EnginnerId);
                    newPlan.setFseName(pdList.get(i).getFseName());
                    newPlan.setIsAccept("1");
                    newPlan.setEstimatedDepartureTime(sdf.parse(estimatedDepartureTime));
                    newPlan.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
                    newPlan.setEstimatedWorkingHours(estimatedWorkingHours);
                    newPlan.setSignOffAutoHour(signOffAutoHour);
                    newPlan.setState("1");
                    newPlan.setCreateTime(date);
                    newPlan.setAcceptTime(date);
                    PlanDetails planDetailsSearch = new PlanDetails();
                    planDetailsSearch.setServiceNo(pdList.get(i).getServiceNo());
                    planDetailsSearch.setFseId(EnginnerId);
                    planDetailsSearch.setIsAccept("1");
                    List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);

                    if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList)) {
                        if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList.get(0).getAcceptTime())) {
                            newPlan.setAcceptTime(planDetailsListlanDetailsList.get(0).getAcceptTime());
                        }
                    }


                    planDetailsMapper.insertStPlanDetails(newPlan);

                    ServiceDetails serviceDetails = new ServiceDetails();
                    serviceDetails.setFseId(EnginnerId);
                    serviceDetails.setState(Long.parseLong("3"));
                    serviceDetails.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                    serviceDetails.setUpdateBy(newPlan.getId() + "");
                    serviceDetailsMapper.updateMyServiceDetails(serviceDetails);

                    PlanDetails planDetails = new PlanDetails();
                    planDetails.setId(pdList.get(i).getId());
                    planDetails.setSignOff("1");
                    planDetails.setSignOffLon(Double.parseDouble(longitude));
                    planDetails.setSignOffLat(Double.parseDouble(latitude));
                    planDetails.setState(state);
                    planDetails.setSignOffTime(date);
                    planDetails.setSignOffAutoHour(signOffAutoHour);
                    planDetailsMapper.updateStPlanDetails(planDetails);

                    // 离线返回处理
                    Map<String, String> offLineData = new HashMap<>();

                    ServiceDetails detailTemp = new ServiceDetails();
                    detailTemp.setFseId(EnginnerId);
                    detailTemp.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                    detailTemp.setServiceNo(pdList.get(i).getServiceNo());
                    List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(detailTemp);
                    ServiceDetails details = serviceDetailsList.get(0);
                    offLineData.put("serviceNo", detailTemp.getServiceNo());
                    offLineData.put("serviceNoticeId", detailTemp.getServiceNoticeId() + "");
                    offLineData.put("planId", details.getUpdateBy());
                    offLineData.put("state", "3");
                    offLineData.put("serviceType", serviceNotice1.getServiceType());
                    offLineData.put("subServiceType", serviceNotice1.getSubServiceType());

                    InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(details.getServiceNo());
                    offLineData.put("instrumentId", instrumentInfo.getId() + "");
                    offLineData.put("instSn", instrumentInfo.getInstSn());
                    PlanDetails temp = planDetailsMapper.selectStPlanDetailsById(new Long(details.getUpdateBy()));
                    offLineData.put("acceptTime", sdf.format(temp.getAcceptTime()));
                    offLineDatas.add(offLineData);
                }
                // 有服务报告 并且 已经提交 已完成。
                if (reportInfoList.size() >= 1) {
                    ServiceDetails serviceDetails = new ServiceDetails();
                    serviceDetails.setFseId(EnginnerId);
                    serviceDetails.setState(Long.parseLong("4"));
                    serviceDetails.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                    serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                    PlanDetails planDetails = new PlanDetails();
                    planDetails.setId(pdList.get(i).getId());
                    planDetails.setSignOff("1");
                    planDetails.setSignOffLon(Double.parseDouble(longitude));
                    planDetails.setSignOffLat(Double.parseDouble(latitude));
                    planDetails.setState("4");
                    planDetails.setSignOffTime(date);
                    planDetails.setSignOffAutoHour(signOffAutoHour);
                    planDetailsMapper.updateStPlanDetails(planDetails);

                    // 离线处理
                    Map<String, String> offLineData = new HashMap<>();
                    ServiceDetails detailTemp = new ServiceDetails();
                    detailTemp.setFseId(EnginnerId);
                    detailTemp.setServiceNoticeId(pdList.get(i).getServiceNoticeId());
                    detailTemp.setServiceNo(pdList.get(i).getServiceNo());
                    List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(detailTemp);
                    ServiceDetails details = serviceDetailsList.get(0);
                    offLineData.put("serviceNo", detailTemp.getServiceNo());
                    offLineData.put("serviceNoticeId", detailTemp.getServiceNoticeId() + "");
                    offLineData.put("planId", details.getUpdateBy());
                    offLineData.put("state", "4");
                    offLineData.put("serviceType", serviceNotice1.getServiceType());
                    offLineData.put("subServiceType", serviceNotice1.getSubServiceType());

                    InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(details.getServiceNo());
                    offLineData.put("instrumentId", instrumentInfo.getId() + "");
                    offLineData.put("instSn", instrumentInfo.getInstSn());

                    PlanDetails temp = planDetailsMapper.selectStPlanDetailsById(new Long(details.getUpdateBy()));
                    offLineData.put("acceptTime", sdf.format(temp.getAcceptTime()));
                    offLineDatas.add(offLineData);

                }


                /** 更新操作日志表 */
                BatchLog batchLog = new BatchLog();
                batchLog.setEnginnerId(Long.parseLong(EnginnerId));
                batchLog.setPlanId(pdList.get(i).getId());
                batchLog.setServiceNo(pdList.get(i).getServiceNo());
                batchLog.setCreateTime(date);
                batchLog.setBatchType(2L);
                batchLogMapper.insertBatchLog(batchLog);


            }

            /** 调用高德api 根据经纬线逆解析用户所在地址 */
            String address = "";
            String url = global.getGaodeApi().replaceAll("KEY", global.getGaodeKey())
                    .replaceAll("LOCATION", longitude + "," + latitude);
            Response res = OkHttpUtils.getInstance().getRequest(url.toString(), null);
            if (res.code() == 200) {
                String reponseBody = res.body().string();
                log.info("高德地址逆解析返回结果：" + reponseBody);
                JSONObject obj = JSON.parseObject(reponseBody);
                if ("1".equals(obj.getString("status"))) {
                    address = obj.getJSONObject("regeocode").getString("formatted_address");
                    log.info("高德逆解析地址：" + address);
                }
            }
            /** 签离位置信息存入log表中，用于轨迹查询 */
            FseLocationLog fseLocationLog = new FseLocationLog();
            fseLocationLog.setAddress(address);
            fseLocationLog.setFseId(EnginnerId);
            List<User> userList = userMapper.getFseInformation(EnginnerId);
            fseLocationLog.setFseName(userList.get(0).getName());
            fseLocationLog.setNetworkState("WWAN");
            fseLocationLog.setState("1");
            fseLocationLog.setPostx(Double.parseDouble(longitude));
            fseLocationLog.setPosty(Double.parseDouble(latitude));
            fseLocationLog.setCreateTime(date);
            fseLocationLog.setReceiveDate(date);
            fseLocationLog.setType("3");
            fseLocationLogMapper.insertFseLocationLog(fseLocationLog);

        }
        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);
    }

    @Override
    public PlanDetails getPlanDetails(PlanDetails stPlanDetails) {
        return planDetailsMapper.getPlanDetails(stPlanDetails);
    }

    @Override
    public ResponseWithData<?> selectFseWorkPlan(Map<String, String> param) {
        List<Map> list = planDetailsMapper.selectFseWorkPlan(param);

        Map<String, String> totalParam = new HashMap<>();
        totalParam.put("type", param.get("type"));
        totalParam.put("isVisited", param.get("isVisited"));
        totalParam.put("startTime", param.get("startTime"));
        totalParam.put("endTime", param.get("endTime"));
        totalParam.put("enginnerId", param.get("enginnerId"));
        totalParam.put("limitNum", null);

        //List<Map> list2=new ArrayList<>();
        List<Map> totallist = planDetailsMapper.selectFseWorkPlan(totalParam);

        return new ResponseWithData<>().success(list).msg("查询成功" + totallist.size()).code(200);
    }

    @Override
    public int updatePlanWidthIds(Map<String, String> planDetails) {

        planDetails.put("updateTime", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        return planDetailsMapper.updatePlanWidthIds(planDetails);
    }

    @Override
    public ResponseWithData<?> signOffAutoState(String serviceNoticeId, String enginnerId, String planId) throws Exception {
        // 更新服务详情表状态为已完成
        ServiceDetails serviceDetails = new ServiceDetails();
        serviceDetails.setState(4L);
        serviceDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
        serviceDetails.setFseId(enginnerId);
        serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
        // 更新计划详情表
        PlanDetails planDetails = new PlanDetails();
        planDetails.setId(Long.parseLong(planId));
        planDetails.setState("4");
//        PlanDetails planDetailsSearch = new PlanDetails();
//        planDetailsSearch.setServiceNoticeId(new Long(serviceNoticeId));
//        planDetailsSearch.setFseId(enginnerId);
//        List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);
//        if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList)) {
//            if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList.get(0).getAcceptTime())) {
//                planDetails.setAcceptTime(planDetailsListlanDetailsList.get(0).getAcceptTime());
//            }
//        }
        planDetailsMapper.updateStPlanDetails(planDetails);

        // 离线数据处理
        List<Map<String, String>> offLineDatas = new ArrayList<>();

        // 离线返回处理
        Map<String, String> offLineData = new HashMap<>();
        ServiceDetails detailTemp = new ServiceDetails();
        detailTemp.setFseId(enginnerId);
        detailTemp.setServiceNoticeId(new Long(serviceNoticeId));
        List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(detailTemp);
        ServiceDetails details = serviceDetailsList.get(0);
        offLineData.put("serviceNo", details.getServiceNo());
        offLineData.put("serviceNoticeId", details.getServiceNoticeId() + "");
        offLineData.put("planId", details.getUpdateBy());
        offLineDatas.add(offLineData);

        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);
    }

    @Override
    public ResponseWithData<?> fseSignOffAutoAgain(String serviceNoticeId, String serviceNo, String enginnerId, String planId, String estimatedVisitingTime, String estimatedWorkingHours, String estimatedDepartureTime, Double signOffAutoHour) throws Exception {
        // 离线数据处理
        List<Map<String, String>> offLineDatas = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        PlanDetails planDetails6 = new PlanDetails();
//        planDetails6.setFseId(enginnerId);
//        planDetails6.setState("'1','2','3'");
//        planDetails6.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
//        planDetails6.setPlanIds(planId);
//        List<PlanDetails> planDetailsL = planDetailsMapper.checkPlanDetailsList(planDetails6);
//        if(planDetailsL!=null && planDetailsL.size()>0){
//            return new ResponseWithData<>().error().msg("预计上门时间冲突").code(201);
//        }

        // 更新服务详情表状态为已完成
        ServiceDetails serviceDetails = new ServiceDetails();
        serviceDetails.setState(3L);
        serviceDetails.setServiceNoticeId(Long.parseLong(serviceNoticeId));
        serviceDetails.setFseId(enginnerId);
        serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
        // 更新计划详情表
        PlanDetails planDetails = new PlanDetails();
        planDetails.setId(Long.parseLong(planId));
        planDetails.setState("3");
//        PlanDetails planDetailsSearchT =  new PlanDetails();
//        planDetailsSearchT.setServiceNoticeId(new Long(serviceNoticeId));
//        planDetailsSearchT.setFseId(enginnerId);
//        List<PlanDetails> planDetailsListT = planDetailsMapper.selectStPlanDetailsList(planDetailsSearchT);
//        planDetails.setAcceptTime(new Date());
//        if (!ObjectUtils.isEmpty(planDetailsListT)) {
//            if (!ObjectUtils.isEmpty(planDetailsListT.get(0).getAcceptTime())) {
//                planDetails.setAcceptTime(planDetailsListT.get(0).getAcceptTime());
//            }
//        }
        planDetailsMapper.updateStPlanDetails(planDetails);

        PlanDetails planDetails2 = planDetailsMapper.selectStPlanDetailsById(Long.parseLong(planId));


        //判断是否该加计划

        PlanDetails planDetailstemp = new PlanDetails();
        planDetailstemp.setServiceNoticeId(new Long(serviceNoticeId));
        planDetailstemp.setFseId(enginnerId);
        planDetailstemp.setState("1");
        List<PlanDetails> planDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailstemp);
        if (planDetailsList.size() < 1) {
            PlanDetails planDetails1 = new PlanDetails();
            planDetails1.setServiceNoticeId(planDetails2.getServiceNoticeId());
            planDetails1.setServiceNo(planDetails2.getServiceNo());
            planDetails1.setFseId(planDetails2.getFseId());
            planDetails1.setFseName(planDetails2.getFseName());
            planDetails1.setServiceRole(planDetails2.getServiceRole());
            planDetails1.setIsAccept("1");
            planDetails1.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
            planDetails1.setEstimatedWorkingHours(estimatedWorkingHours);
            planDetails1.setEstimatedDepartureTime(sdf.parse(estimatedDepartureTime));
            planDetails1.setIsDoor(planDetails2.getIsDoor());
            planDetails1.setIsBorrow(planDetails2.getIsBorrow());
            planDetails1.setCreateTime(new Date());
            planDetails1.setAcceptTime(new Date());
            planDetails1.setSignOffAutoHour(signOffAutoHour);
            PlanDetails planDetailsSearch = new PlanDetails();
            planDetailsSearch.setServiceNo(planDetails2.getServiceNo());
            planDetailsSearch.setFseId(planDetails2.getFseId());
            planDetailsSearch.setIsAccept("1");
            List<PlanDetails> planDetailsListlanDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);
            if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList)) {
                if (!ObjectUtils.isEmpty(planDetailsListlanDetailsList.get(0).getAcceptTime())) {
                    planDetails1.setAcceptTime(planDetailsListlanDetailsList.get(0).getAcceptTime());
                }
            }

            planDetails1.setState("1");
            planDetailsMapper.insertStPlanDetails(planDetails1);

            //更新 ServiceDetails update_by

            //查询最新的信息
            ServiceDetails serviceDetailstemp = new ServiceDetails();

            PlanDetails planDetailsNew = new PlanDetails();
            planDetailsNew.setFseId(planDetails2.getFseId());
            planDetailsNew.setServiceNoticeId(planDetails2.getServiceNoticeId());
            List<PlanDetails> planDetailsList2 = planDetailsMapper.selectStPlanDetailsList(planDetailsNew);

            if (planDetailsList2.size() > 0) {
                serviceDetailstemp.setUpdateBy(planDetailsList2.get(0).getId() + "");
            }
            serviceDetailstemp.setServiceNoticeId(Long.parseLong(serviceNoticeId));
            serviceDetailstemp.setFseId(enginnerId);
            serviceDetailsMapper.updateMyServiceDetails(serviceDetailstemp);

            // 离线数据处理
            Map<String, String> offLineData = new HashMap<>();

            ServiceDetails detailTemp = new ServiceDetails();
            detailTemp.setFseId(enginnerId);
            detailTemp.setServiceNoticeId(Long.parseLong(serviceNoticeId));
            detailTemp.setServiceNo(serviceNo);
            List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(detailTemp);
            ServiceDetails details = serviceDetailsList.get(0);
            offLineData.put("serviceNo", details.getServiceNo());
            offLineData.put("serviceNoticeId", details.getServiceNoticeId() + "");
            offLineData.put("planId", details.getUpdateBy());
            offLineData.put("state", "3");
            ServiceNotice serviceNotice1 = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(serviceNoticeId));
            offLineData.put("serviceType", serviceNotice1.getServiceType());
            offLineData.put("subServiceType", serviceNotice1.getSubServiceType());

            InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(details.getServiceNo());
            offLineData.put("instrumentId", instrumentInfo.getId() + "");
            offLineData.put("instSn", instrumentInfo.getInstSn());

            // 查询最新的计划
            PlanDetails planDetailTemp = new PlanDetails();
            planDetailTemp.setServiceNoticeId(new Long(serviceNoticeId));
            planDetailTemp.setFseId(enginnerId);
            planDetailTemp.setIsAccept("1");
            planDetailTemp.setSignIn("0");
            PlanDetails planDetailsSignIn = planDetailsMapper.getPlanDetailsBySignInByNoticeId(planDetailTemp);
            offLineData.put("acceptTime", sdf.format(planDetailsSignIn.getAcceptTime()));

            offLineDatas.add(offLineData);
        }
        return new ResponseWithData<>().success(offLineDatas).msg("操作成功").code(200);


    }

    @Override
    public ResponseWithData<?> fseFillLogCount(String enginnerId) throws Exception {
        List<PlanDetails> planDetails = planDetailsMapper.fseFillLogCount(enginnerId);
        return new ResponseWithData<>().success(planDetails).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> updateEstimatedVisitingTime(String planId, String enginnerId, String estimatedVisitingTime, String estimatedWorkingHours, String estimatedDepartureTime, Double signOffAutoHour) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        PlanDetails planDetails = new PlanDetails();
//        planDetails.setFseId(enginnerId);
//        planDetails.setState("'1','2','3'");
//        planDetails.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
//        planDetails.setEstimatedDepartureTime(sdf.parse(estimatedDepartureTime));
//        planDetails.setPlanIds(planId);
//        List<PlanDetails> planDetails1 = planDetailsMapper.checkPlanDetailsList(planDetails);
//        if(planDetails1!=null && planDetails1.size()>0){
//            return new ResponseWithData<>().error().msg("预计上门时间冲突").code(201);
//        }
        PlanDetails planDetails2 = new PlanDetails();
        planDetails2.setId(Long.parseLong(planId));
        planDetails2.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
        planDetails2.setEstimatedWorkingHours(estimatedWorkingHours);
        planDetails2.setEstimatedDepartureTime(sdf.parse(estimatedDepartureTime));
        planDetails2.setSignOffAutoHour(signOffAutoHour);
        planDetailsMapper.updateStPlanDetails(planDetails2);
        return new ResponseWithData<>().success().msg("更新成功").code(200);
    }

    @Override
    public List<PlanDetails> selectWorkPlanList(Map<String, Object> params) {
        return planDetailsMapper.selectWorkPlanListModify(params);
    }

    @Override
    public PlanDetails selectOldPlanDetailId(PlanDetails planDetails) {
        List<PlanDetails> list = planDetailsMapper.selectOldPlanDetailId(planDetails);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return new PlanDetails();
    }

    @Override
    public PlanDetails selectAllOldPlanDetailId(PlanDetails planDetails) {
        List<PlanDetails> list = planDetailsMapper.selectStPlanDetailsList(planDetails);
        //TODO
        //需要判断 最后一个状态是不是1，返回最后一个状态不是1的plan
        if (list != null && list.size() >= 1) {
            PlanDetails planDetailslast1, planDetailslast2;
            if (list.size() == 1) {
                planDetailslast1 = list.get(0);
                if ("1".equals(planDetailslast1.getState())) {
                    return null;
                } else {
                    return planDetailslast1;
                }
            } else {
                planDetailslast1 = list.get(0);
                planDetailslast2 = list.get(1);
                if ("1".equals(planDetailslast1.getState())) {
                    return planDetailslast2;
                } else {
                    return planDetailslast1;
                }
            }
        }
        return null;
    }

    @Override
    public ResponseWithData<?> checkPlanDetailsList(String planId, String enginnerId, String estimatedVisitingTime, String estimatedDepartureTime) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        PlanDetails planDetails = new PlanDetails();
        planDetails.setFseId(enginnerId);
        planDetails.setState("'1','2','3'");
        planDetails.setEstimatedVisitingTime(sdf.parse(estimatedVisitingTime));
        planDetails.setEstimatedDepartureTime(sdf.parse(estimatedDepartureTime));
        planDetails.setPlanIds(planId);
        List<PlanDetails> planDetails1 = planDetailsMapper.checkPlanDetailsList(planDetails);
        if (planDetails1 != null && planDetails1.size() > 0) {
            return new ResponseWithData<>().error().msg("预计上门时间冲突").code(201);
        } else {
            return new ResponseWithData<>().error().msg("不冲突").code(200);
        }
    }
}
